<template>
    <div class="slider" ref="slider">
        <div class="slider-group" ref="sliderGroup">
            <slot></slot>
        </div>
        <div class="dots">
            <span class="dot" v-for="(item, index) in dots"
                  :class="{active: currentPageIndex === index}"
                  :key="index"
            >
            </span>
        </div>
    </div>
</template>

<script type="text/ecmascript-6">
    import BSroll from 'better-scroll'
    import { addClass } from 'common/js/dom'
    import { REFRESH_TIME } from 'common/js/config'

    // 轮播图主动滑动的切换速度
    const SLIDE_TIME = 400
    // 轮播图自动播放的速度
    const PLAY_TIME = 1000

    export default {
        name: 'slider',
        data() {
            return {
                dots: [],
                currentPageIndex: 0
            }
        },
        props: {
            // 循环轮播
            loop: {
                type: Boolean,
                default: true
            },
            // 自动轮播
            autoPlay: {
                type: Boolean,
                default: true
            },
            // 轮播间隔
            interval: {
                type: Number,
                default: 4000
            }
        },
        mounted() {
            setTimeout(() => {
                this._setSliderWidth()
                // dots的初始必须在slider前
                // bscroll为了实现无缝循环滚动会额外添加两个item
                this._initDots()
                this._initSlider()

                if (this.autoPlay) {
                    this._play()
                }
            }, REFRESH_TIME)
            // 监听窗口大小改变事件
            window.addEventListener('resize', () => {
                if (!this.slider) {
                    return
                }
                this._setSliderWidth(true)
                this.slider.refresh()
            })
        },
        methods: {
            // 计算轮播图宽度
            _setSliderWidth(isResize) {
                // 轮播图片数组
                this.children = this.$refs.sliderGroup.children

                // 累加记录轮播图总宽度
                let width = 0
                let sliderWidth = this.$refs.slider.clientWidth

                for (let i = 0, len = this.children.length; i < len; i++) {
                    let child = this.children[i]
                    addClass(child, 'slider-item')
                    child.style.width = `${sliderWidth}px`
                    width += sliderWidth
                }
                // 如果轮播图是循环播放，择需要在前后各加上一个图片位置
                if (this.loop && !isResize) {
                    width += 2 * sliderWidth
                }
                // 设置轮播图宽度
                this.$refs.sliderGroup.style.width = `${width}px`
            },
            _initDots() {
                this.dots = new Array(this.children.length)
            },
            // slider初始化
            _initSlider() {
                this.slider = new BSroll(this.$refs.slider, {
                    scrollX: true,
                    scrollY: false,
                    // 惯性
                    momentum: false,
                    snap: true,
                    // 循环
                    snapLoop: this.loop,
                    snapThreshold: 0.5,
                    // 滑动速度
                    snapSpeed: SLIDE_TIME,
                    click: true
                })
                // 监听滑动停止事件
                this.slider.on('scrollEnd', () => {
                    // 获得当前展示图片的索引
                    let pageIndex = this.slider.getCurrentPage().pageX
                    // 对循环展示的索引做适配
                    if (this.loop) {
                        pageIndex -= 1
                    }
                    this.currentPageIndex = pageIndex

                    if (this.autoPlay) {
                        clearTimeout(this.timer)
                        this._play()
                    }
                })
            },
            // 轮播图自动播放
            _play() {
                let pageIndex = this.currentPageIndex + 1
                if (this.loop) {
                    pageIndex += 1
                }
                this.timer = setTimeout(() => {
                    this.slider.goToPage(pageIndex, 0, PLAY_TIME)
                }, this.interval)
            }

        },
        destroyed() {
            // 清理计算器
            clearTimeout(this.timer)
        },
        deactivated() {
            // 清理计算器
            clearTimeout(this.timer)
        },
        activated() {
            this._setSliderWidth(true)
            this.slider.refresh()
            this._play()
        }
    }
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
    @import "~common/stylus/variable"
    .slider
        margin-top: 5px
        min-height: 1px
        .slider-group
            position: relative
            overflow: hidden
            white-space: nowrap
            .slider-item
                float: left
                box-sizing: border-box
                padding: 0 15px
                overflow: hidden
                text-align: center
                .a
                    display: block
                    width: 100%
                    overflow: hidden
                    text-decoration: none
                .img
                    display: block
                    width: 100%
                    border-radius: 10px
        .dots
            position: absolute
            right: 0
            left: 0
            bottom: 10px
            transform: translateZ(1px)
            text-align: center
            font-size: 0
            .dot
                display: inline-block
                margin: 0 3px
                width: 6px
                height: 6px
                border-radius: 50%
                background: $color-text-w-l
                transition: width .2s
                &.active
                    width: 15px
                    border-radius: 5px
                    background: $color-text-w-ll

</style>
